<template>
  <!-- 角色表单弹窗 -->
  <Modal :modelValue="modelValue" :title="title" @close="handleCloseDialog" @open="handleOpenDialog">
    <div class="flex-x-between">
      <el-input v-model="permKeywords" clearable class="w-[200px]" placeholder="菜单权限名称">
        <template #prefix>
          <i-ep-search />
        </template>
      </el-input>

      <div class="flex-center">
        <el-button type="primary" size="small" plain @click="togglePermTree"><i-ep-switch />{{ isExpanded ? "收缩" :
          "展开"
          }}</el-button>
        <el-checkbox v-model="parentChildLinked" @change="handleparentChildLinkedChange" class="ml-5">父子联动
        </el-checkbox>

        <el-tooltip placement="bottom">
          <template #content> 如果只需勾选菜单权限，不需要勾选子菜单或者按钮权限，请关闭父子联动 </template>
          <i-ep-QuestionFilled class="ml-1 color-[--el-color-primary] inline-block cursor-pointer" />
        </el-tooltip>
      </div>
    </div>

    <el-tree ref="permTreeRef" node-key="menu_id" show-checkbox :data="menuTreeData"
      :filter-node-method="handlePermFilter" :default-expand-all="true" :check-strictly="!parentChildLinked"
      class="mt-5">
      <template #default="{ data }">
        {{ data.title }}
      </template>
    </el-tree>

    <template #footer>
      <div class="modal-footer">
        <el-button type="primary" @click="handleAssignPermSubmit">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </Modal>
</template>

<script setup lang="ts">
import RoleMenuAPI, { RoleMenuForm, RoleMenuVO } from '@/api/role-menu';
import MenuAPI, { MenuVO } from '@/api/menu';
import RoleAPI, { RolePageVO } from '@/api/role';
import { buildTree } from '@/utils';

// 定义接收的属性
interface Props {
  modelValue: boolean
  selectedItem: RolePageVO
  title?: string
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '表单',
})

// 自定义事件
const emit = defineEmits<{
  submit: []
  close: []
}>()

const permTreeRef = ref<InstanceType<typeof ElTree>>()

const loading = ref(false)

// 菜单权限下拉
const menuTreeData = ref<MenuVO[]>([])

const permKeywords = ref("")
const isExpanded = ref(true)

const parentChildLinked = ref(true)

const selectedRole = ref<RolePageVO>({})

const handleOpenDialog = () => {

}
const handleCloseDialog = () => {
  emit('close')
}


const getMenuTree = async () => {
  // 获取所有的菜单
  const res = await MenuAPI.query()
  if (res.status === 200) {
    menuTreeData.value = buildTree(res.data, "menu_id", "pid")
  }

  // 回显角色已拥有的菜单
  const queryConditon: QueryCondition = {
    and: [{ field: "role_id", "op": "=", value: selectedRole.value.role_id }]
  }
  RoleMenuAPI.query(queryConditon).then((res) => {
    const { status, data } = res
    if (status === 200) {
      const checkedMenuroleIds = data
      checkedMenuroleIds.forEach((item) => permTreeRef.value!.setChecked(item.menu_id as any, true, false))
    }
  }).finally(() => {
    loading.value = false
  })
}
/** 分配菜单权限提交 */
const handleAssignPermSubmit = async () => {
  const roleId = selectedRole.value.role_id
  if (roleId) {
    loading.value = true
    const deleteCondition: QueryCondition = {
      _cond: { and: [{ field: "role_id", "op": "=", value: roleId }] }
    }
    //先删除
    await RoleMenuAPI.deleteByCondition(deleteCondition)
    //构建新增
    const nodes = permTreeRef.value!.getCheckedNodes(false, true)
    const roleMenuList: RoleMenuForm[] = []
    if (nodes && nodes.length) {
      nodes.forEach((node) => {
        const roleMenu: RoleMenuForm = {
          role_id: roleId,
          menu_id: node.menu_id
        }
        roleMenuList.push(roleMenu)
      })
    }
    RoleMenuAPI.saveBatch(roleMenuList).then((res) => {
      if (res.status === 200) {
        ElMessage.success("分配权限成功")
        emit('submit')
      }
    }).finally(() => {
      loading.value = false
    })
  }
}

/** 展开/收缩 菜单权限树  */
const togglePermTree = () => {
  isExpanded.value = !isExpanded.value;
  if (permTreeRef.value) {
    Object.values(permTreeRef.value.store.nodesMap).forEach((node: any) => {
      if (isExpanded.value) {
        node.expand();
      } else {
        node.collapse();
      }
    });
  }
}

/** 父子菜单节点是否联动 change*/
const handleparentChildLinkedChange = (val: any) => {
  parentChildLinked.value = val
}


//表单传递数据
watch(() => props.selectedItem, (newVal, oldVal) => {
  Object.assign(selectedRole.value, newVal)

  getMenuTree()
}, { immediate: true, deep: true })

/** 权限筛选  */
watch(permKeywords, (val) => {
  permTreeRef.value!.filter(val)
})

function handlePermFilter(
  value: string,
  data: {
    [key: string]: any
  }
) {
  if (!value) return true
  return data.label.includes(value)
}



</script>
